package TwentyEighthDay;

import java.util.*;

public class PermuteUnique {
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length == 0){
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        backTracking(nums, nums.length, path, used, res);
        return res;
    }

    private void backTracking(int[] nums, int index, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
        if (index == 0){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]){
                continue;
            }
            if (!used[i - 1] && nums[i] == nums[i - 1] && i > 0){
                continue;
            }
            used[i] = true;
            path.add(nums[i]);
            backTracking(nums, index - 1, path, used, res);
            path.removeLast();
            used[i] = false;
        }
    }

}
